import React, { useState } from 'react';
import { Treemap, ResponsiveContainer, Tooltip } from 'recharts';
import { useDiaryStore } from '../../store/diaryStore';
import { useChartContext } from '../../contexts/ChartContext';

interface TagTreemapChartProps {
  maxTags?: number;
  minSize?: number;
}

interface TreemapData {
  name: string;
  size: number;
  count: number;
  color: string;
  children?: TreemapData[];
  [key: string]: any; // Index signature for Recharts compatibility
}

const TagTreemapChart: React.FC<TagTreemapChartProps> = ({ maxTags = 20, minSize = 1 }) => {
  const entries = useDiaryStore((state) => state.entries);
  const getPopularTags = useDiaryStore((state) => state.getPopularTags);
  const { filters, setFilters } = useChartContext();
  const [viewMode, setViewMode] = useState<'flat' | 'categorized'>('flat');
  const [selectedTag, setSelectedTag] = useState<string | null>(null);

  // Color palette for different categories and tags
  const colorPalette = [
    '#3b82f6', '#ef4444', '#10b981', '#f59e0b', '#8b5cf6',
    '#06b6d4', '#ec4899', '#84cc16', '#f97316', '#6366f1',
    '#14b8a6', '#f43f5e', '#22c55e', '#a855f7', '#0ea5e9',
    '#eab308', '#dc2626', '#059669', '#7c3aed', '#0891b2'
  ];

  // Categorize tags based on common patterns
  const categorizeTag = (tag: string): string => {
    const lowerTag = tag.toLowerCase();
    
    if (['work', 'job', 'career', 'meeting', 'project', 'deadline'].some(w => lowerTag.includes(w))) {
      return 'Work';
    }
    if (['family', 'mom', 'dad', 'sister', 'brother', 'parent', 'child'].some(w => lowerTag.includes(w))) {
      return 'Family';
    }
    if (['friend', 'social', 'party', 'hangout', 'chat', 'call'].some(w => lowerTag.includes(w))) {
      return 'Social';
    }
    if (['health', 'exercise', 'gym', 'run', 'walk', 'fitness', 'doctor'].some(w => lowerTag.includes(w))) {
      return 'Health';
    }
    if (['travel', 'vacation', 'trip', 'holiday', 'flight', 'hotel'].some(w => lowerTag.includes(w))) {
      return 'Travel';
    }
    if (['hobby', 'read', 'book', 'music', 'movie', 'game', 'art', 'cook'].some(w => lowerTag.includes(w))) {
      return 'Hobbies';
    }
    if (['learn', 'study', 'course', 'school', 'education', 'skill'].some(w => lowerTag.includes(w))) {
      return 'Learning';
    }
    
    return 'Other';
  };

  // Generate treemap data
  const generateTreemapData = (): TreemapData[] => {
    const popularTags = getPopularTags(maxTags).filter(tag => tag.count >= minSize);
    
    if (viewMode === 'flat') {
      return popularTags.map((tag, index) => ({
        name: tag.tag,
        size: tag.count,
        count: tag.count,
        color: colorPalette[index % colorPalette.length]
      }));
    }
    
    // Categorized view
    const categories: Record<string, TreemapData[]> = {};
    
    popularTags.forEach((tag, index) => {
      const category = categorizeTag(tag.tag);
      if (!categories[category]) {
        categories[category] = [];
      }
      
      categories[category].push({
        name: tag.tag,
        size: tag.count,
        count: tag.count,
        color: colorPalette[index % colorPalette.length]
      });
    });
    
    return Object.entries(categories).map(([categoryName, tags], categoryIndex) => {
      const totalSize = tags.reduce((sum, tag) => sum + tag.size, 0);
      return {
        name: categoryName,
        size: totalSize,
        count: tags.length,
        color: colorPalette[categoryIndex % colorPalette.length],
        children: tags
      };
    }).sort((a, b) => b.size - a.size);
  };

  const treemapData = generateTreemapData();
  
  const handleTagClick = (data: TreemapData) => {
    if (data.name && !data.children) {
      const currentTags = filters.tags || [];
      const isSelected = currentTags.includes(data.name);
      const newTags = isSelected 
        ? currentTags.filter(tag => tag !== data.name)
        : [...currentTags, data.name];
      
      setFilters({ tags: newTags });
      setSelectedTag(isSelected ? null : data.name);
    }
  };

  const clearSelection = () => {
    setSelectedTag(null);
    setFilters({ tags: [] });
  };

  const CustomTooltip = ({ active, payload }: any) => {
    if (active && payload && payload.length) {
      const data = payload[0].payload;
      return (
        <div className="bg-white p-3 border border-warm-gray-200 rounded-lg shadow-lg">
          <p className="font-medium text-warm-gray-800">{data.name}</p>
          <p className="text-sm text-warm-gray-600">
            {data.children ? `${data.count} tags, ${data.size} total uses` : `Used ${data.count} times`}
          </p>
          {!data.children && (
            <p className="text-xs text-blue-600 mt-1 cursor-pointer">
              Click to filter by this tag
            </p>
          )}
        </div>
      );
    }
    return null;
  };

  const CustomContent = (props: any) => {
    const { x, y, width, height, name, size, color, children } = props;
    
    // Don't render if too small
    if (width < 20 || height < 20) return null;
    
    const isSelected = filters.tags?.includes(name) || false;
    const opacity = isSelected ? 1 : 0.8;
    
    return (
      <g>
        <rect
          x={x}
          y={y}
          width={width}
          height={height}
          fill={isSelected ? '#3b82f6' : color}
          fillOpacity={opacity}
          stroke={isSelected ? '#1f2937' : '#ffffff'}
          strokeWidth={isSelected ? 2 : 1}
          className="cursor-pointer transition-all duration-200 hover:stroke-gray-600 hover:stroke-2"
          onClick={() => handleTagClick(props)}
        />
        
        {/* Text label */}
        {width > 40 && height > 20 && (
          <text
            x={x + width / 2}
            y={y + height / 2}
            textAnchor="middle"
            dominantBaseline="middle"
            className="fill-white text-xs font-medium pointer-events-none select-none"
            style={{
              fontSize: Math.min(width / 8, height / 3, 12),
              textShadow: '1px 1px 2px rgba(0,0,0,0.7)'
            }}
          >
            {name.length > width / 8 ? name.substring(0, Math.floor(width / 8)) + '...' : name}
          </text>
        )}
        
        {/* Size label for larger rectangles */}
        {width > 60 && height > 40 && (
          <text
            x={x + width / 2}
            y={y + height / 2 + 12}
            textAnchor="middle"
            dominantBaseline="middle"
            className="fill-white text-xs opacity-90 pointer-events-none select-none"
            style={{
              fontSize: Math.min(width / 12, height / 4, 10),
              textShadow: '1px 1px 2px rgba(0,0,0,0.7)'
            }}
          >
            {children ? `${size} uses` : size}
          </text>
        )}
      </g>
    );
  };

  return (
    <div className="bg-white rounded-lg shadow-sm border border-warm-gray-200 p-6">
      <div className="flex items-center justify-between mb-4">
        <h3 className="text-lg font-semibold text-warm-gray-800">
          Tag Usage Treemap
        </h3>
        <div className="flex items-center gap-2">
          <select
            value={viewMode}
            onChange={(e) => setViewMode(e.target.value as 'flat' | 'categorized')}
            className="text-xs border border-warm-gray-300 rounded px-2 py-1 focus:outline-none focus:ring-2 focus:ring-blue-500"
          >
            <option value="flat">Flat View</option>
            <option value="categorized">Categorized</option>
          </select>
          {filters.tags && filters.tags.length > 0 && (
            <button
              onClick={clearSelection}
              className="text-xs bg-red-100 text-red-700 px-2 py-1 rounded hover:bg-red-200 transition-colors"
            >
              Clear Selection
            </button>
          )}
        </div>
      </div>

      {filters.tags && filters.tags.length > 0 && (
        <div className="mb-4 p-3 bg-blue-50 rounded-lg">
          <p className="text-sm text-blue-800">
            Filtered by tags: <span className="font-medium">{filters.tags.join(', ')}</span>
          </p>
        </div>
      )}

      {treemapData.length === 0 ? (
        <div className="flex items-center justify-center h-64 text-warm-gray-500">
          <div className="text-center">
            <p className="text-lg mb-2">No tag data available</p>
            <p className="text-sm">Start adding tags to your entries to see usage patterns</p>
          </div>
        </div>
      ) : (
        <div className="h-96">
          <ResponsiveContainer width="100%" height="100%">
            <Treemap
              data={treemapData}
              dataKey="size"
              aspectRatio={4/3}
              stroke="#ffffff"
              content={<CustomContent />}
            >
              <Tooltip content={<CustomTooltip />} />
            </Treemap>
          </ResponsiveContainer>
        </div>
      )}

      <div className="mt-4 text-xs text-warm-gray-500">
        <div className="flex items-center justify-between">
          <p>
            <strong>Tip:</strong> Rectangle size represents tag usage frequency. Click to filter entries.
          </p>
          <p className="text-right">
            Showing top {maxTags} tags with {minSize}+ uses
          </p>
        </div>
        {viewMode === 'categorized' && (
          <p className="mt-1">
            Tags are automatically categorized by content (Work, Family, Social, Health, etc.)
          </p>
        )}
      </div>
    </div>
  );
};

export default TagTreemapChart;